import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2024-03-22
 * Time: 9:03
 */
public class SeqList {
    private int[] elem;
    private int usedSize;

    public static final int DEFAULT_CAPACITY = 10;

    public SeqList() {
        this.elem = new int[DEFAULT_CAPACITY];
    }
    //打印顺序表
    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
    // 新增元素,默认在数组最后新增
    public void add(int data) {
        // 满了的情况,就要扩容
        if(isFull()) {
            resize();
        }
        this.elem[usedSize] = data;
        this.usedSize++;
    }
    // 判定是否包含某个元素
    public boolean contains(int data) {
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == data) {
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind) {
               return i;
            }
        }
        return -1;
    }
    // 获取顺序表长度
    public int size() {
        return this.usedSize;
    }
    // 获取 pos 位置的元素
    public int get(int pos) {
        //1.要检查pos位置合不合法
        if(!checkPos(pos)) {
            throw new PosOutOfBounds("pos位置不合法: " + pos);
        }
        return elem[pos];
    }
    // 给 pos 位置的元素设为 value (更新的意思)
    public void set(int pos,int value) {
        //1.要检查pos位置合不合法
        if(!checkPos(pos)) {
            throw new PosOutOfBounds("pos位置不合法: " + pos);
        }
        this.elem[pos] = value;
    }

    private boolean checkPos(int pos) {
        if(pos < 0 || pos >= this.usedSize) {
            return false;
        }
        return true;
    }
    // 在 pos 位置新增元素
    public void add(int pos, int value) {
        if(pos < 0 || pos > this.usedSize) {
            throw new PosOutOfBounds("pos位置不合法: " + pos);
        }
        if(isFull()) {
            resize();
        }
        for (int i = this.usedSize-1; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = value;
        this.usedSize++;
    }
    private boolean isFull() {
        if(this.usedSize == this.elem.length) {
            return true;
        }
        return false;
    }
    private void resize() {
        this.elem = Arrays.copyOf(this.elem,this.elem.length*2);
    }

    private boolean isEmpty() {
        return this.usedSize == 0;
    }
    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        if(isEmpty()) {
            return;
        }
        int del = indexOf(toRemove);
        if(del == -1) {
            return;
        }
        for (int i = del; i < this.usedSize-1; i++) {
            elem[i] = elem[i+1];
        }
        this.usedSize--;
    }
    // 清空顺序表
    public void clear() {
        this.usedSize = 0;
    }
}
